const fs = require("fs");

toSchool(
  require("./淮阳区/src/淮阳区学校.json"),
  "淮阳区/dist/淮阳区学校.json"
);
toTown(require("./淮阳区/src/淮阳区地址.json"), "淮阳区/dist/淮阳区地址.json");

function toTown(data, filename) {
  const getChildren = (data) => {
    const newData = [];

    for (const key in data) {
      const item = data[key];

      if (Array.isArray(item)) {
        const children = item.map((item) => {
          return {
            text: item.name,
            value: item.name,
          };
        });

        newData.push({
          text: key,
          value: key,
          children: children,
        });
      } else if (typeof item == "object") {
        newData.push({
          text: key,
          value: key,
          children: getChildren(item),
        });
      }
    }

    return newData;
  };

  const newData = getChildren(data);

  console.log("newData", newData);

  fs.writeFileSync(filename, JSON.stringify(newData, null, "\t"));
}

// function toTown(data, filename) {
//   const getChildren = (data) => {
//     const newData = [];

//     for (const key in data) {
//       const item = data[key];

//       if (typeof item == "object") {
//         newData.push({
//           text: key,
//           value: key,
//           children: getChildren(item),
//         });
//       } else {
//         newData.push({
//           text: item,
//           value: item,
//         });
//       }
//     }

//     return newData;
//   };

//   const newData = getChildren(data);

//   fs.writeFileSync(filename, JSON.stringify(newData, null, "\t"));
// }

function toSchool(data, filename) {
  const newData = [];
  for (const key in data) {
    const item = data[key];

    const children = item.map((val) => {
      return {
        text: val,
        value: val,
      };
    });

    newData.push({
      text: key,
      value: key,
      children,
    });
  }

  fs.writeFileSync(filename, JSON.stringify(newData, null, "\t"));
}
